import React, { useState, useRef, useEffect, useCallback } from 'react';
import './VideoFeed.css';
import axios from 'axios';
import { io, Socket } from 'socket.io-client';

let socket: Socket | null = null;
/**
 * 视频数据接口定义
 */
interface VideoData {
  id: number;
  url: string;
  title: string;
  likes: number;
  favorites: number;
}

/**
 * 抖音风格的视频浏览组件
 * 支持上下滑动切换视频、点赞、收藏功能
 */
const VideoFeed: React.FC = () => {

  const [videoList, setVideoList] = useState<VideoData[]>([]);
   const getVideoList = useCallback(async () => {
    try {
      const res = await axios.get('vlist');
      setVideoList(res.data.videoList);
    } catch (error) {
      console.error('获取视频列表失败:', error);
    }
  }, []);

 useEffect(() => {
    getVideoList();

    // 创建 socket 连接
    if (!socket) {
      socket = io('http://localhost:3000', {
        withCredentials: true,
        transports: ['websocket']
      });

      socket.on('connect', () => {
        console.log('VideoFeed Socket connected!');
      });
    }

    // 监听数据更新事件
    socket.on('dataUpdate', () => {
      console.log('收到数据更新事件');
      getVideoList();
    });

    return () => {
      socket?.off('dataUpdate');
    };
  }, [getVideoList]);

  const [currentIndex, setCurrentIndex] = useState(0);
  const [videoStats, setVideoStats] = useState<Map<number, { likes: number; favorites: number }>>(new Map());
  const [likeStates, setLikeStates] = useState<Map<number, boolean>>(new Map());
  const [favoriteStates, setFavoriteStates] = useState<Map<number, boolean>>(new Map());
  const [showContextMenu, setShowContextMenu] = useState(false);
  const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 });
  const [contextMenuType, setContextMenuType] = useState<'like' | 'favorite' | null>(null);
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([]);

  // 初始化视频统计数据和状态
  useEffect(() => {
    const initialStats = new Map();
    const initialLikeStates = new Map();
    const initialFavoriteStates = new Map();
    videoList.forEach(video => {
      initialStats.set(video.id, { likes: video.likes || 0, favorites: video.favorites || 0 });
      initialLikeStates.set(video.id, true); // 默认为激活状态
      initialFavoriteStates.set(video.id, true); // 默认为激活状态
    });
    setVideoStats(initialStats);
    setLikeStates(initialLikeStates);
    setFavoriteStates(initialFavoriteStates);
  }, [videoList]);

  // 点击其他地方关闭右键菜单
  useEffect(() => {
    const handleClickOutside = () => setShowContextMenu(false);
    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, []);

  /**
   * 处理视频滚动切换
   * @param direction 滚动方向：1向下，-1向上
   */
  const handleScroll = (direction: number) => {
    const newIndex = currentIndex + direction;
    if (newIndex >= 0 && newIndex < videoList.length) {
      videoRefs.current[currentIndex]?.pause();
      setCurrentIndex(newIndex);
      videoRefs.current[newIndex]?.play();
    }
  };

  // 错误日志记录函数
  const logError = async (errorType: string, fieldType: string, title: string, description: string) => {
    try {
      await axios.post('http://localhost:3000/logError', {
        source: 'Frontend',
        errorType,
        fieldType,
        title,
        description,
        timestamp: new Date().toISOString().replace('T', ' ').split('.')[0]
      });
    } catch (logErr) {
      console.error('记录错误日志失败:', logErr);
    }
  };

  /**
   * 发送数据到后端
   * @param videoId 视频ID
   * @param action 操作类型：'like' 或 'favorite'
   * @param count 增加或减少的数量（负数表示减少）
   * @returns Promise<boolean> 返回操作是否成功
   */
  const sendToBackend = async (videoId: number, action: 'like' | 'favorite', count: number = 1000): Promise<boolean> => {
    try {
      await axios.post('vEdit', {
        videoId:11111,
        action,
        count
      });
      console.log(`${action} 操作成功:`, videoId, `变化${count}`);
      return true;
    } catch (error) {
      console.error('发送数据失败:', error);
      await logError('NetworkError', 'HTTPResponse', '后端请求失败', `错误详情: ${error instanceof Error ? error.message : String(error)}`);
      return false;
    }
  };

  /**
   * 处理点赞操作
   * @param videoId 视频ID
   * @param count 增加的点赞数量，默认1000
   */
  const handleLike = async (videoId: number, count: number = 1000) => {
    // 先更新本地状态
    setVideoStats(prev => {
      const newStats = new Map(prev);
      const currentStats = newStats.get(videoId) || { likes: 0, favorites: 0 };
      newStats.set(videoId, { ...currentStats, likes: currentStats.likes + count });
      return newStats;
    });
    
    // 发送到后端
    const success = await sendToBackend(videoId, 'like', count);
    if (!success) {
      // 如果后端请求失败，回滚本地状态
      setVideoStats(prev => {
        const newStats = new Map(prev);
        const currentStats = newStats.get(videoId) || { likes: count, favorites: 0 };
        newStats.set(videoId, { ...currentStats, likes: Math.max(0, currentStats.likes - count) });
        return newStats;
      });
      await logError('UIError', 'LikeOperation', '点赞操作失败', `视频ID: ${videoId}, 错误: 后端请求失败`);
    }
  };

  /**
   * 处理取消点赞操作
   * @param videoId 视频ID
   */
  const handleUnlike = async (videoId: number) => {
    const currentStats = videoStats.get(videoId) || { likes: 0, favorites: 0 };
    const reduceCount = Math.min(1000, currentStats.likes); // 最多减少1000，不能为负数
    
    // 先更新本地状态
    setVideoStats(prev => {
      const newStats = new Map(prev);
      newStats.set(videoId, { ...currentStats, likes: Math.max(0, currentStats.likes - reduceCount) });
      return newStats;
    });
    
    setLikeStates(prev => {
      const newStates = new Map(prev);
      newStates.set(videoId, false);
      return newStates;
    });
    
    // 发送到后端（负数表示减少）
    const success = await sendToBackend(videoId, 'like', -reduceCount);
    if (!success) {
      // 如果后端请求失败，回滚本地状态
      setVideoStats(prev => {
        const newStats = new Map(prev);
        newStats.set(videoId, currentStats);
        return newStats;
      });
      setLikeStates(prev => {
        const newStates = new Map(prev);
        newStates.set(videoId, true);
        return newStates;
      });
      await logError('UIError', 'UnlikeOperation', '取消点赞操作失败', `视频ID: ${videoId}, 错误: 后端请求失败`);
    }
  };

  /**
   * 处理+100红心操作
   * @param videoId 视频ID
   */
  const handleLike100 = async (videoId: number) => {
    try {
      await handleLike(videoId, 100);
    } catch (error) {
      await logError('UIError', 'LikeOperation', '+100点赞操作失败', `视频ID: ${videoId}, 错误: ${error instanceof Error ? error.message : String(error)}`);
    }
  };

  /**
   * 处理+100000红心操作
   * @param videoId 视频ID
   */
  const handleLike100000 = async (videoId: number) => {
    try {
      await handleLike(videoId, 100000);
    } catch (error) {
      await logError('UIError', 'LikeOperation', '+100000点赞操作失败', `视频ID: ${videoId}, 错误: ${error instanceof Error ? error.message : String(error)}`);
    }
  };

  /**
   * 处理收藏操作
   * @param videoId 视频ID
   */
  const handleFavorite = async (videoId: number) => {
    // 先更新本地状态
    setVideoStats(prev => {
      const newStats = new Map(prev);
      const currentStats = newStats.get(videoId) || { likes: 0, favorites: 0 };
      newStats.set(videoId, { ...currentStats, favorites: currentStats.favorites + 1000 });
      return newStats;
    });
    
    // 发送到后端
    const success = await sendToBackend(videoId, 'favorite');
    if (!success) {
      // 如果后端请求失败，回滚本地状态
      setVideoStats(prev => {
        const newStats = new Map(prev);
        const currentStats = newStats.get(videoId) || { likes: 0, favorites: 1000 };
        newStats.set(videoId, { ...currentStats, favorites: Math.max(0, currentStats.favorites - 1000) });
        return newStats;
      });
      await logError('UIError', 'FavoriteOperation', '收藏操作失败', `视频ID: ${videoId}, 错误: 后端请求失败`);
    }
  };

  /**
   * 处理取消收藏操作
   * @param videoId 视频ID
   */
  const handleUnfavorite = async (videoId: number) => {
    const currentStats = videoStats.get(videoId) || { likes: 0, favorites: 0 };
    const reduceCount = Math.min(1000, currentStats.favorites); // 最多减少1000，不能为负数
    
    // 先更新本地状态
    setVideoStats(prev => {
      const newStats = new Map(prev);
      newStats.set(videoId, { ...currentStats, favorites: Math.max(0, currentStats.favorites - reduceCount) });
      return newStats;
    });
    
    setFavoriteStates(prev => {
      const newStates = new Map(prev);
      newStates.set(videoId, false);
      return newStates;
    });
    
    // 发送到后端（负数表示减少）
    const success = await sendToBackend(videoId, 'favorite', -reduceCount);
    if (!success) {
      // 如果后端请求失败，回滚本地状态
      setVideoStats(prev => {
        const newStats = new Map(prev);
        newStats.set(videoId, currentStats);
        return newStats;
      });
      setFavoriteStates(prev => {
        const newStates = new Map(prev);
        newStates.set(videoId, true);
        return newStates;
      });
      await logError('UIError', 'UnfavoriteOperation', '取消收藏操作失败', `视频ID: ${videoId}, 错误: 后端请求失败`);
    }
  };

  /**
   * 处理右键菜单显示
   * @param e 鼠标事件
   * @param type 菜单类型
   */
  const handleContextMenu = (e: React.MouseEvent, type: 'like' | 'favorite') => {
    e.preventDefault();
    setContextMenuPosition({ x: e.clientX, y: e.clientY });
    setContextMenuType(type);
    setShowContextMenu(true);
  };

  /**
   * 处理右键菜单点击
   */
  const handleContextMenuClick = () => {
    const videoId = videoList[currentIndex]?.id;
    if (!videoId) return;
    
    if (contextMenuType === 'like') {
      handleUnlike(videoId);
    } else if (contextMenuType === 'favorite') {
      handleUnfavorite(videoId);
    }
    
    setShowContextMenu(false);
  };

  return (
    <div className="video-feed-container">
      <div className="video-wrapper">
        <video
          ref={(el: HTMLVideoElement | null) => {
            if (videoRefs.current) {
              videoRefs.current[currentIndex] = el;
            }
          }}
          src={videoList[currentIndex]?.url}
          loop
          autoPlay
          playsInline
          className="video-player"
        />
        <div className="video-controls">
          
          <button 
            onClick={() => handleLike(videoList[currentIndex]?.id)} 
            onContextMenu={(e) => handleContextMenu(e, 'like')}
            className="control-button"
            style={{ 
              color: likeStates.get(videoList[currentIndex]?.id) ? '#ff6b6b' : '#888',
              opacity: likeStates.get(videoList[currentIndex]?.id) ? 1 : 0.5 
            }}
          >
            ❤️ {videoStats.get(videoList[currentIndex]?.id)?.likes || 0}
          </button>
          <button onClick={() => handleLike100(videoList[currentIndex]?.id)} className="control-button">
            ❤️ +100红心
          </button>
          <button onClick={() => handleLike100000(videoList[currentIndex]?.id)} className="control-button">
            ❤️ +100000红心
          </button>
          <button 
            onClick={() => handleFavorite(videoList[currentIndex]?.id)} 
            onContextMenu={(e) => handleContextMenu(e, 'favorite')}
            className="control-button"
            style={{ 
              color: favoriteStates.get(videoList[currentIndex]?.id) ? '#ffd93d' : '#888',
              opacity: favoriteStates.get(videoList[currentIndex]?.id) ? 1 : 0.5 
            }}
          >
            ⭐ {videoStats.get(videoList[currentIndex]?.id)?.favorites || 0}
          </button>
        </div>
        
        <div className="navigation-buttons">
          <button
            onClick={() => handleScroll(-1)}
            disabled={currentIndex === 0}
            className="nav-button"
          >
            ⬆️
          </button>
          <button
            onClick={() => handleScroll(1)}
            disabled={currentIndex === videoList.length - 1}
            className="nav-button"
          >
            ⬇️
          </button>
        </div>
      </div>
      
      {/* 右键菜单 - 移到最外层容器 */}
      {showContextMenu && (
        <div 
          className="context-menu"
          style={{
            position: 'fixed',
            left: contextMenuPosition.x,
            top: contextMenuPosition.y,
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            border: '1px solid rgba(255, 255, 255, 0.3)',
            borderRadius: '8px',
            padding: '12px 16px',
            boxShadow: '0 8px 25px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(255, 255, 255, 0.1)',
            backdropFilter: 'blur(15px)',
            zIndex: 9999,
            cursor: 'pointer',
            color: '#333',
            fontSize: '14px',
            fontWeight: '500',
            transition: 'all 0.2s ease',
            userSelect: 'none'
          }}
          onClick={handleContextMenuClick}
          onMouseEnter={(e) => {
            e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 1)';
            e.currentTarget.style.transform = 'scale(1.02)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.95)';
            e.currentTarget.style.transform = 'scale(1)';
          }}
        >
          {contextMenuType === 'like' ? '取消红心' : '取消收藏'}
        </div>
      )}
    </div>
  );
};

export default VideoFeed;